document.addEventListener('DOMContentLoaded', function () {
    const token = localStorage.getItem('access_token');
    // 绑定修改按钮事件
    function bindEditButtons() {
        const editButtons = document.querySelectorAll('.edit-btn');

        editButtons.forEach(button => {
            button.addEventListener('click', function () {
                const typeId = button.getAttribute('data-id');
                const currentName = button.previousElementSibling.textContent;
                
                // 弹出输入框获取新的课程类型名称
                const newName = prompt('请输入新的课程类型名称：', currentName);

                if (newName && newName.trim() !== '') {
                    // 发送修改请求到后端
                    fetch(`/api/course-types/${typeId}/`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token}`,
                            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                        },
                        body: JSON.stringify({
                            type_name: newName.trim()
                        })
                    })
                    .then(response => {
                        if (response.ok) {
                            // 更新页面上的课程类型名称
                            button.previousElementSibling.textContent = newName.trim();
                        } else {
                            throw new Error('修改失败');
                        }
                    })
                    .catch(error => {
                        console.error('错误:', error);
                        alert('修改失败，请稍后再试！');
                    });
                }
            });
        });
    }

    // 绑定删除按钮事件
    function bindDeleteButtons() {
        const deleteButtons = document.querySelectorAll('.delete-btn');

        deleteButtons.forEach(button => {
            button.addEventListener('click', function (event) {
                event.preventDefault(); 
                const typeId = button.getAttribute('data-id');
                if (confirm('确定要删除该课程类型吗？')) {
                    fetch(`/api/course-types/${typeId}/`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                            'Authorization': `Bearer ${token}`,
                        }
                    })
                    .then(response => {
                        if (response.ok) {
                            const listItem = button.closest('li');
                            listItem.remove();
                        } else {
                            throw new Error('删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('错误:', error);
                        alert('删除失败，请稍后再试！');
                    });
                }
            });
        });
    }

    bindEditButtons();
    bindDeleteButtons();
});